import pymysql
import os
from common.read_data import data
from common.logger import logger
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
data_file_path = os.path.join(BASE_DIR, 'config','setting.ini')
data = data.load_ini(data_file_path)['mysql']

DB_CONF = {
    "host": data['MYSQL_HOST'],
    "port": int(data['MYSQL_PORT']),
    "user": data['MYSQL_USER'],
    "password": data['MYSQL_PASSWD'],
    "database": data['MYSQL_DB'],
}

class MysqlOperate:
    def __init__(self,db_conf = DB_CONF):
        self.conn = pymysql.connect(**db_conf,autocommit=True)
        self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

    def __del__(self):
        self.conn.close()
        self.cursor.close()

    def select_db(self,sql):
       '''查询'''
       # 检查连接是否断开，如果断开进行重连
       self.conn.ping(reconnect=True)
       self.cursor.execute(sql)
       # 使用fetchall()获取查询结果
       data = self.cursor.fetchall()
       return data
    def execute_db(self,sql):
        '''更新/新增/删除'''
        try:
            # 检查是否断开，断开重连
            self.conn.ping(reconnect=True)
            self.cursor.execute(sql)
            # 提交事物
            self.conn.commit()
        except Exception as e:
            logger.info(f'操作mysql出现错误，错误原因为：{e}')
            # 回滚所有更改
            self.conn.rollback()
db = MysqlOperate(DB_CONF)
if __name__ == '__main__':
    aa = db.select_db('select * from student')[0]
    print(aa)

